import { createStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/plugins/axios';
import { resetRouter, initPermissionRouters } from '@/router/permission-routers';
import tools from '@/utils/tools';

const { removeToken, removeRefreshToken } = tools;

let ElMessageBoxInstance;

export default createStore({
    state() {
        return {
            language: window.localStorage.getItem('lang') || 'zh-CN',
            // 是否已经获取过菜单及权限
            permissionReady: false,
            menus: [],
            permissions: [],
            roles: [],
            userInfo: {},
            // 已打开的菜单tag
            visitedViews: [],
            // 已打开的菜单tag中，需要做缓存的菜单
            cachedViews: new Set()
        };
    },
    mutations: {
        updateLanguage(state, lang) {
            state.language = lang;
            window.localStorage.setItem('lang', lang);
        },
        setPermissions(state, data) {
            const { menus, permissions, roles, user } = data || {};
            state.menus = menus;
            state.permissions = permissions;
            state.roles = roles;
            state.userInfo = user;
            state.permissionReady = true;
        },
        clearPermissions(state) {
            state.menus = [];
            state.permissions = [];
            state.roles = [];
            state.userInfo = {};
            state.permissionReady = false;
        },
    },
    actions: {
        getPermissions(ctx) {
            return new Promise((resolve, reject) => {
                axios.get('/system/auth/get-permission-info').then(async (res) => {
                    const data = (res.data || {}).data || {};
                    ctx.commit('setPermissions', data);
                    if (!data.menus || !data.menus.length) {
                        ElMessage.warning('暂未配置菜单权限，请联系管理员');
                        const fullPath = (window.location.href.split('/#') || [])[1];
                        const path = fullPath.includes('/login') ? '/login' : `/login?redirect=${fullPath.replace(/\?redirect=\/[^?]*/, '')}`;
                        reject(path);
                        return;
                    }
                    await initPermissionRouters(data.menus);
                    resolve(res);
                }).catch(() => {
                    const option = {
                        message: '菜单权限获取失败，请刷新页面重试，或者尝试重新登录',
                        showCancelButton: true,
                        cancelButtonText: '刷新页面',
                        cancelCallback() {
                            window.location.reload();
                        },
                    };
                    ctx.dispatch('handleAskRelogin', option);
                    reject();
                });
            });
        },
        handleAskRelogin({ commit }, option = {}) {
            if (ElMessageBoxInstance) return;
            const message = option.message || '登陆状态已失效，是否重新登录？';
            ElMessageBoxInstance = ElMessageBox.confirm(message, {
                title: '系统提示',
                showCancelButton: false,
                closeOnClickModal: false,
                showClose: false,
                confirmButtonText: '重新登录',
                type: 'warning',
                ...option,
            }).then(() => {
                commit('clearPermissions');
                removeToken();
                removeRefreshToken();
                resetRouter();
                if (option.confirmCallback) option.confirmCallback();
            }).catch(option.cancelCallback || (() => { })).finally(() => {
                ElMessageBoxInstance = null;
            });
        },
    },
});
